package isquirrel.servlets;

import isquirrel.FacebookAPI;
import isquirrel.UserManager;
import isquirrel.beans.Friend;
import isquirrel.beans.Interest;
import isquirrel.beans.User;
import isquirrel.error.CannotLoginUserException;
import isquirrel.servlets.handler.HttpDBServlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.json.JSONException;

/**
 * Servlet implementation class FriendSuggestions
 */
public class FriendSuggestions extends HttpDBServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FriendSuggestions() {
        super();
        // TODO Auto-generated constructor stub
    }

	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		
		/* compress information to shrink loading times */
		String encoding = request.getHeader("Accept-Encoding");    
	    OutputStream out = null;
		if (encoding != null && encoding.indexOf("gzip") != -1){
			 response.setHeader("Content-Encoding" , "gzip");
		     out = new GZIPOutputStream(response.getOutputStream());
		}
		else if (encoding != null && encoding.indexOf("compress") != -1){
			 response.setHeader("Content-Encoding" , "compress");
			 out = new ZipOutputStream(response.getOutputStream());
		} 
		else{
			 out = response.getOutputStream();
		}
		
		User crnt_user = UserManager.getUser((String)request.getSession().getAttribute("user"));
		FacebookAPI api = new FacebookAPI();
		
		List<User> searchSet = UserManager.getUsers();
		searchSet.removeAll(crnt_user.getFriends());
		searchSet.remove(crnt_user);
		
		if (searchSet.size() < 1){
			String outstr = new String("<p style='font-size:0.78em; color: #aaa'>No suggestions found.");
			out.write(outstr.getBytes());
		}
		else{
			
			Vector<Friend> orderedSet = new Vector<Friend>();

			for (User u: searchSet){
				orderedSet.add(new Friend(
									u.getFullName(), 
									u.getFbID(), 
									u.getUserID(), 
									null,
									u.getLikedUrls().size(),
									crnt_user.compare(u)));
			}
			Collections.sort(orderedSet);
			orderedSet.setSize(2);

			for(Friend f : orderedSet){
				
				StringBuffer outstr = new StringBuffer();
			
				if (f == null) continue;
				User u = UserManager.getUser(f.getUserID());
				String pic = "/" + request.getRequestURI().split("/")[1] + "/images/";
				if (u.getFbID() == 0){ 
					pic += (u.getSex().equals("Male")) ? "nopicmale.png" : "nopicfemale.png";
 				}
				else{
					pic = api.getUser_PicSquare(String.valueOf(f.getFbID()));
				}
				if (pic == null){
					// rarely the fb call returns null so to avoid any exceptions from setting img.src = null
					// we set the image to a 'no image' pic.
					pic = "/" + request.getRequestURI().split("/")[1] + "/images/";
					pic += (crnt_user.getSex().equals("Male")) ? "nopicmale.png" : "nopicfemale.png";
				}
			
				f.setPic(pic);
					
				outstr.append("<div id='" + f.getUserID() + "' style='width:100%;height:110px;' class='friendsuggestion'>");
				outstr.append("<img class='friendimg' src='" + f.getPic() + "' />");
				outstr.append("<div style='width:70%;margin-bottom:8px;' class='frienddetails'>"
							 + "<div style='font-weight:bold' class='friendname'>" + f.getName() + "</div>");
				
				if (crnt_user.getFriends().contains(u)) {
					outstr.append("<div style='font-weight:bold;position:relative; left:0; top:0' class='stopfollow' onclick='stopfollow(this," + u.getUserID() + ")'>Remove from friends</div>");
				}
				else{
					outstr.append("<div style='font-weight:bold;position:relative; left:0; top:0' class='follow' onclick='follow(this," + u.getUserID() + ")'>Add to friends</div>");
				}
				
				outstr.append("<div>Liked " + f.getLikes() +" pages.</div></div><br><br>");
				outstr.append("<div style='margin-top:2px;margin-bottom:2px;margin-left:0;padding-left:0' class='frienddetails'>"
							 + "Interests: "
							 + "<b>" 
							 );
				
				Iterator<Interest> it = u.getInterests().iterator();
			    String interests = "";
			    while (it.hasNext()){
					interests += it.next().getLabel() + ", ";
			    }
			 	if (interests.equals("")){
					interests = "None (so far).";
				}
				else{
					interests = interests.substring(0, interests.length() - 2);
				}
				String tooltip = interests;
				if (interests.length() > 40) interests = interests.substring(0,40).trim() + "...";

				outstr.append("<span title='" + tooltip + "'>" + interests + "</span></b></div>");
		        outstr.append("<div style='margin-bottom:1px;margin-left:0;padding-left:0' class=frienddetails>"
		        			+ "Profile match: " + f.getProfileMatch_formatted() 
		        			+ "</div></div>"
		        
		        );
		        out.write(new String(outstr).getBytes());
			}
		}
		out.close();
	}

	@Override
	protected void handlePost() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		// TODO Auto-generated method stub
		
	}

}
